import { buildings, ids, initRecipes } from './defs'
import { addRecipe } from './game'
import { world } from './store'
import { ItemDelta, Recipe } from './type'

/** 解析配方 */
export const parseRecipe = (s: string, k = -1): ItemDelta[] =>
	s ? s.split(',').map(s => {
		const [count, name] = s.split(/(\D+)/, 2)
		return [ids.get(name)!, k * +count]
	}) : []

/** 配方字符串 */
export const recipeStr = (s: string, k = 1) =>
	s.split(',').map(s => {
		const [count, name] = s.split(/(\D+)/, 2)
		return k * +count + name
	}).join()

export function getRecipes(building: number) {
	return recipes.filter(r => {
		if (r.reqTechs) {
			for (const tech of r.reqTechs)
				if (!world.techs.has(tech))
					return false
		}
		return r.buildings.has(building)
	})
}

export function recipe(name: string, building: string, deltas: ItemDelta[],
	period = 1, reqTechs = '') {
	return {
		id: addRecipe(deltas),
		name,
		period,
		deltas,
		buildings: building ? new Set(building.split(',')
			.map(name => buildings.find(b => b.name == name)!.id)) : new Set<number>(),
		reqTechs: reqTechs ? new Set(reqTechs.split(',')) : void 0,
	}
}

/** 配方列表 */
export const recipes: Recipe[] = []

/** 初始化配方 */
export { initRecipes }
